﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using _4chanManager.Panels;

namespace _4chanManager
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly List<TabItem> _tabItems;
        private readonly TabItem _tabAdd;

        public MainWindow()
        {
            InitializeComponent();

            _tabItems = new List<TabItem>();
            _tabAdd = new TabItem {Header = "+", Content = new AddTabMenu()};

            _tabItems.Add(_tabAdd);

            tcTabs.DataContext = _tabItems;

            tcTabs.SelectedIndex = 0;
        }
        

        private void TcTabs_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabItem tab = tcTabs.SelectedItem as TabItem;
            if (tab == null) return;

            if (tab.Equals(_tabAdd))
            {
                // clear tab control binding
                tcTabs.DataContext = null;

                TabItem newTab = this.AddTabItem();

                // bind tab control
                tcTabs.DataContext = _tabItems;

                // select newly added tab item
                tcTabs.SelectedItem = newTab;
            }
            else
            {
                // your code here...
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            string tabName = ((Button) sender).CommandParameter.ToString();

            var item = tcTabs.Items.Cast<TabItem>().FirstOrDefault(i => i.Name.Equals(tabName));

            TabItem tab = item;

            if (tab == null) return;
         
            TabItem selectedTab = tcTabs.SelectedItem as TabItem;

            tcTabs.DataContext = null;

            _tabItems.Remove(tab);

            tcTabs.DataContext = _tabItems;

            if (selectedTab == null || selectedTab.Equals(tab))
            {
                selectedTab = _tabItems[0];
            }
            tcTabs.SelectedItem = selectedTab;
            
        }

        private TabItem AddTabItem()
        {
            int count = _tabItems.Count;

            TabItem tab = new TabItem
            {
                Header = string.Format("Tab {0}", count),
                Name = string.Format("tab{0}", count),
                HeaderTemplate = tcTabs.FindResource("TabHeader") as DataTemplate,   
            };
            tab.Content = new AddTabMenu(tab);
            _tabItems.Insert(count - 1, tab);

            return tab;
        }
    }
}
